package com.yylending.remotevideo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.*;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.*;

import com.bairuitech.anychat.AnyChatBaseEvent;
import com.bairuitech.anychat.AnyChatCoreSDK;
import com.bairuitech.anychat.AnyChatDefine;
import com.bairuitech.anychat.AnyChatObjectDefine;
import com.bairuitech.anychat.AnyChatObjectEvent;
import com.bairuitech.anychat.AnyChatVideoCallEvent;
import com.yyfax.common.CLog;
import com.yylending.remotevideo.config.BaseMethod;

public class RemoteVideoActivity extends Activity implements AnyChatBaseEvent,
		OnTouchListener, AnyChatObjectEvent, AnyChatVideoCallEvent {
	private static final String TAG = "RemoteVideoActivity";

	public static final int REQUEST_CODE = 1001;

	public static final int MSG_CHECKAV = 1;
	public static final int MSG_TIMEUPDATE = 2;
	public static final int PROGRESSBAR_HEIGHT = 5;

	private boolean bSelfVideoOpened = false;
	private boolean bOtherVideoOpened = false;
	private boolean bVideoViewLoaded = false;

	private int dwTargetUserId;
	private int mRoomId;

	private int videoIndex = 0;
	private int videocallSeconds = 0;

	private LinearLayout layoutLocal;

	private SurfaceView mSurfaceSelf;
	private SurfaceView mSurfaceRemote;
	private ProgressBar mProgressSelf;
	private ProgressBar mProgressRemote;

	private TextView mTxtTime;

	private AnyChatCoreSDK anychat;
	private Handler mHandler;
	private Timer mTimerCheckAv;
	private Timer mTimerShowVideoTime;
	private TimerTask mTimerTask;
//	private ConfigEntity configEntity;
	/**翻转摄像头*/
	private View mSwitchCamera;

	public static void start(Activity aty, int userId, int roomId) {
		Intent i = new Intent(aty, RemoteVideoActivity.class);
		i.putExtra("userId", userId);
		i.putExtra("roomId", roomId);
		aty.startActivityForResult(i, REQUEST_CODE);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return keyCode != KeyEvent.KEYCODE_BACK && super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		releaseMediaResources();
		anychat.removeEvent(this);
		mTimerCheckAv.cancel();
		mTimerShowVideoTime.cancel();
		anychat.LeaveRoom(-1);//已经在返回的Activity里走了销毁流程
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		initSdk();
		if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {
			videoIndex = anychat.mVideoHelper.bindVideo(mSurfaceRemote.getHolder());
			anychat.mVideoHelper.SetVideoUser(videoIndex, dwTargetUserId);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		initSdk();
		initView();
		updateAV();
	}

	/**
	 * 初始化sdk
	 */
	private void initSdk() {
		if (anychat == null)
			anychat = AnyChatCoreSDK.getInstance(this);//new AnyChatCoreSDK();
		anychat.SetBaseEvent(this);
		anychat.SetVideoCallEvent(this);
		anychat.SetObjectEvent(this);
		anychat.mSensorHelper.InitSensor(getApplicationContext());// 启动AnyChat传感器监听
		AnyChatCoreSDK.mCameraHelper.SetContext(getApplicationContext());
	}

	/**
	 * 实时音视频
	 */
	private void updateAV() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
					case MSG_CHECKAV:
						checkVideoStatus();//实时视频刷新
						updateVolume();//实时音频数据
						break;
					case MSG_TIMEUPDATE:
						mTxtTime.setText(BaseMethod.getTimeShowString(videocallSeconds++));
						break;
				}
			}
		};
		initTimerCheckAv();
		initTimerShowTime();
	}

	private void initTimerCheckAv() {
		if (mTimerCheckAv == null)
			mTimerCheckAv = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(MSG_CHECKAV);
			}
		};
		mTimerCheckAv.schedule(mTimerTask, 1000, 100);
	}

	private void initTimerShowTime() {
		if (mTimerShowVideoTime == null)
			mTimerShowVideoTime = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(MSG_TIMEUPDATE);
			}
		};
		mTimerShowVideoTime.schedule(mTimerTask, 100, 1000);
	}

	/**
	 * 初始化布局
	 */
	private void initView() {
		setContentView(R.layout.activity_remote_video);

		Intent ii = getIntent();
		if (ii != null) {
			dwTargetUserId = ii.getIntExtra("userId", -1);
			mRoomId = ii.getIntExtra("roomId", -1);
			CLog.i(TAG, "TargetUserId = " + dwTargetUserId + ", RoomId = " + mRoomId);
			anychat.EnterRoom(mRoomId, "");//在新界面才进入房间
		} else {
			CLog.i(TAG, "RV.Intent is null, can't enter room");
		}

		mSurfaceSelf = (SurfaceView) findViewById(R.id.surface_local);
		mSurfaceRemote = (SurfaceView) findViewById(R.id.surface_remote);
		mProgressSelf = (ProgressBar) findViewById(R.id.progress_local);
		mProgressRemote = (ProgressBar) findViewById(R.id.progress_remote);
		mTxtTime = (TextView) findViewById(R.id.txt_time);
		mSwitchCamera = findViewById(R.id.camera_switch);
		mSwitchCamera.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					CLog.i(TAG, "mSwitchCamera.onClick()");
					// 如果是采用Java视频采集，则在Java层进行摄像头切换
					if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
						CLog.i(TAG, "using java method");
						AnyChatCoreSDK.mCameraHelper.SwitchCamera();
						return;
					}
					//如果不是采用Java视频采集，则使用SDK进行摄像头切换
					String strVideoCaptures[] = anychat.EnumVideoCapture();// 枚举本地视频采集设备
					String temp = anychat.GetCurVideoCapture();
					for (int i = 0; i < strVideoCaptures.length; i++) {
						if (!temp.equals(strVideoCaptures[i])) {
							CLog.i(TAG, "using sdk method");
							anychat.UserCameraControl(-1, 0);//0表示关闭摄像头
							bSelfVideoOpened = false;
							anychat.SelectVideoCapture(strVideoCaptures[i]);// 选择指定的视频采集设备
							anychat.UserCameraControl(-1, 1);//1表示打开摄像头
							break;
						}
					}
				} catch (Exception e) {
					Toast.makeText(RemoteVideoActivity.this, "切换摄像头失败", Toast.LENGTH_LONG).show();
				}
			}
		});

		mSurfaceRemote.setTag(dwTargetUserId);

//		configEntity = ConfigService.LoadConfig(this);
//		if (configEntity.videoOverlay != 0) {
			CLog.i(TAG, "设置mSurfaceSelf为推送端");
			mSurfaceSelf.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//		}
		mSurfaceSelf.setZOrderOnTop(true);
		mSurfaceSelf.setZOrderMediaOverlay(true);
		mSurfaceRemote.setZOrderOnTop(true);
		// 视频如果是采用java采集
		if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
			CLog.i(TAG, "视频采用java采集（录制）");
			mSurfaceSelf.getHolder().addCallback(AnyChatCoreSDK.mCameraHelper);
		}

		// 视频显示如果是采用java采集，SurfacecallBack
		if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {
			videoIndex = anychat.mVideoHelper.bindVideo(mSurfaceRemote.getHolder());
			CLog.i(TAG, "视频显示采用java采集（播放）" + videoIndex + ", " + dwTargetUserId);
			anychat.mVideoHelper.SetVideoUser(videoIndex, dwTargetUserId);
		}

		layoutLocal = (LinearLayout) findViewById(R.id.frame_local_area);
		// 默认设置前置摄像头
		layoutLocal.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				if (!bVideoViewLoaded) {
					bVideoViewLoaded = true;
				}
			}
		});
		if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
			if (AnyChatCoreSDK.mCameraHelper.GetCameraNumber() > 1) {
				mSwitchCamera.setVisibility(View.VISIBLE);
				AnyChatCoreSDK.mCameraHelper.SelectVideoCapture(AnyChatCoreSDK.mCameraHelper.CAMERA_FACING_FRONT);//使用前置摄像头
			}
		} else {
			String[] strVideoCaptures = anychat.EnumVideoCapture();
			if (strVideoCaptures != null && strVideoCaptures.length > 1) {
				mSwitchCamera.setVisibility(View.VISIBLE);
				for (String strDevices : strVideoCaptures) {
					if (strDevices.contains("Front")) {
//					if (strDevices.contains("Back")) {
						anychat.SelectVideoCapture(strDevices);
						break;
					}
				}
			}
		}
		//设置旋转屏时的操作；
		LinearLayout layoutRemote = (LinearLayout) findViewById(R.id.frame_remote_area);
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//			adjustLocalVideo(layoutLocal, true);
			adjustLocalVideo(layoutRemote, true);
		} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//			adjustLocalVideo(layoutLocal, false);
			adjustLocalVideo(layoutRemote, false);
		}
	}

	public void adjustLocalVideo(LinearLayout layoutLocal, boolean bLandScape) {
		float width, height;
		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		width = (float) dMetrics.widthPixels / 4;

		int w = AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_WIDTHCTRL);
		int h = AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_HEIGHTCTRL);
		CLog.i(TAG, "Server Video Setting: width = " + w + ", height = " + h);

		FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) layoutLocal.getLayoutParams();
		if (bLandScape) {
			CLog.i(TAG, "Land mode");
			if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_WIDTHCTRL) != 0) {
				height = width * h / w + PROGRESSBAR_HEIGHT;
				CLog.i(TAG, "L_1. Remote video width ctrl, height = " + height);
			} else {
				height = (float) 3 / 4 * width + PROGRESSBAR_HEIGHT;
				CLog.i(TAG, "L_2. Local video height ctrl, height = " + height);
			}
		} else {
			CLog.i(TAG, "Vertical mode");
			if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_HEIGHTCTRL) != 0) {
				height = width * w / h + PROGRESSBAR_HEIGHT;
				CLog.i(TAG, "V_1. Remote video height ctrl, height = " + height);
			} else {
				height = (float) 4 / 3 * width + PROGRESSBAR_HEIGHT;
				CLog.i(TAG, "V_2. Local video height ctrl, height = " + height);
			}
		}
		layoutParams.width = (int) width;
		layoutParams.height = (int) height;
		layoutLocal.setLayoutParams(layoutParams);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			adjustLocalVideo(layoutLocal, true);
			AnyChatCoreSDK.mCameraHelper.setCameraDisplayOrientation();
		} else {
			adjustLocalVideo(layoutLocal, false);
			AnyChatCoreSDK.mCameraHelper.setCameraDisplayOrientation();
		}
	}

	public void obtainMediaResources() {
		anychat.UserCameraControl(dwTargetUserId, 1);//1打开
		anychat.UserSpeakControl(dwTargetUserId, 1);
	}

	public void releaseMediaResources() {
		anychat.UserCameraControl(-1, 0);//0关闭
		anychat.UserSpeakControl(-1, 0);
		anychat.UserSpeakControl(dwTargetUserId, 0);
		anychat.UserCameraControl(dwTargetUserId, 0);
	}

	private void checkVideoStatus() {
		if (!bSelfVideoOpened) {
			if (anychat.GetCameraState(-1) == 2 && anychat.GetUserVideoWidth(-1) != 0) {
				CLog.i(TAG, "设置本机视频");
				SurfaceHolder holder = mSurfaceSelf.getHolder();
				if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {//todo 把!=改成==测试是否可行
					int width = anychat.GetUserVideoWidth(-1);
					int height = anychat.GetUserVideoHeight(-1);
					CLog.i(TAG, "本地视频尺寸：" + width + " * " + height);
					holder.setFixedSize(width, height);
					holder.setFormat(PixelFormat.RGB_565);

//					DisplayMetrics dMetrics = new DisplayMetrics();
//					getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
//					double radio = (double) height / (double) width;
//					double rsHeight = dMetrics.heightPixels * radio;
//
//					RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mSurfaceSelf.getLayoutParams();
////					params.width = width;
//					params.height = (int) rsHeight;//height
//					mSurfaceSelf.setLayoutParams(params);
				}

				Surface s = holder.getSurface();
				anychat.SetVideoPos(-1, s, 0, 0, 0, 0);
				bSelfVideoOpened = true;
			}
		}

		if (!bOtherVideoOpened) {
			if (anychat.GetCameraState(dwTargetUserId) == 2 && anychat.GetUserVideoWidth(dwTargetUserId) != 0) {
				CLog.i(TAG, "设置远程视频");
				SurfaceHolder holder = mSurfaceRemote.getHolder();
				if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) != AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {
					int width = anychat.GetUserVideoWidth(-1);
					int height = anychat.GetUserVideoHeight(-1);
					CLog.i(TAG, "1.远程视频尺寸：" + width + " * " + height);
					holder.setFixedSize(width, height);
					holder.setFormat(PixelFormat.RGB_565);
				}
				//使用JAVA采集
				if (AnyChatCoreSDK.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {
					CLog.i(TAG, "2.videoIndex=" + videoIndex + ", dwTargetUserId=" + dwTargetUserId);
					anychat.mVideoHelper.SetVideoUser(videoIndex, dwTargetUserId);
				} else {
					CLog.i(TAG, "3.set video pos");
					Surface s = holder.getSurface();
					anychat.SetVideoPos(dwTargetUserId, s, 0, 0, 0, 0);
				}
				bOtherVideoOpened = true;
			}
		}
	}

	private void updateVolume() {
		mProgressSelf.setProgress(anychat.GetUserSpeakVolume(-1));
		mProgressRemote.setProgress(anychat.GetUserSpeakVolume(dwTargetUserId));
	}

	public void OnAnyChatConnectMessage(boolean bSuccess) {
		CLog.i(TAG, "RV.1.连接服务器成功=" + bSuccess);
	}

	public void OnAnyChatLoginMessage(int dwUserId, int dwErrorCode) {
		CLog.i(TAG, "RV.2.用户登录:userId=" + dwUserId + ", errorCode(0代表成功)=" + dwErrorCode);
	}

	public void OnAnyChatEnterRoomMessage(int dwRoomId, int dwErrorCode) {
		CLog.i(TAG, "RV.3.进入房间:roomId=" + dwRoomId + ", errorCode(0代表成功)=" + dwErrorCode);
		if (dwErrorCode == 0) {
			anychat.UserCameraControl(-1, 1);//打开本地视频，第一个参数用-1表示本地，也可以用本地的真实userid
			anychat.UserSpeakControl(-1, 1);//打开本地音频
			bSelfVideoOpened = false;
		}
	}

	public void OnAnyChatOnlineUserMessage(int dwUserNum, int dwRoomId) {
		CLog.i(TAG, "RV.4.当前房间在线用户消息:房间总人数=" + dwUserNum);
		obtainMediaResources();
		bOtherVideoOpened = false;
	}

	@Override
	public void OnAnyChatUserAtRoomMessage(int dwUserId, boolean bEnter) {
		CLog.i(TAG, "RV.5.用户进入或者离开房间:bEnter(true表示进入房间，反之表示离开房间)=" + bEnter);
		obtainMediaResources();
		bOtherVideoOpened = false;
		if (!bEnter) {
			CLog.i(TAG, "退出房间");
			releaseMediaResources();
			finish();
		}
	}

	public void OnAnyChatLinkCloseMessage(int dwErrorCode) {
		CLog.i(TAG, "RV.6.跟服务器网络断开:errorCode=" + dwErrorCode);
		releaseMediaResources();

		if (dwErrorCode == 0) {
			BaseMethod.showToast("会话已经挂断", this);
		} else {
			BaseMethod.showToast("与服务器断开连接，请检查您的网络", this);
		}
		CLog.i(TAG, "RV.OnAnyChatLinkCloseMessage:" + dwErrorCode);
	}

	@Override
	public void OnAnyChatVideoCallEvent(int dwEventType, int dwUserId, int dwErrorCode, int dwFlags, int dwParam, String userStr) {
		CLog.i(TAG, "RV.7.视频事件流程回调");
		switch (dwEventType) {
			case AnyChatDefine.BRAC_VIDEOCALL_EVENT_REQUEST:
				CLog.i(TAG, "RV.接收到视频呼叫请求");
				break;
			case AnyChatDefine.BRAC_VIDEOCALL_EVENT_REPLY:
				CLog.i(TAG, "RV.视频呼叫重拨");
				break;
			case AnyChatDefine.BRAC_VIDEOCALL_EVENT_START:
				CLog.e(TAG, "RV.会话开始");
				break;
			case AnyChatDefine.BRAC_VIDEOCALL_EVENT_FINISH:
				BaseMethod.showToast("视频通话已结束", RemoteVideoActivity.this);
//				if (mApplication.getUserType() == USERTYPE_AGENT) {
//					AnyChatCoreSDK.ObjectControl(AnyChatObjectDefine.ANYCHAT_OBJECT_TYPE_AGENT, mApplication.getUserID(), AnyChatObjectDefine.ANYCHAT_AGENT_CTRL_FINISHSERVICE, 0, 0, 0, 0, "");
//				}
				break;
		}
	}

	@Override
	public void OnAnyChatObjectEvent(int dwObjectType, int dwObjectId,
			int dwEventType, int dwParam1, int dwParam2, int dwParam3,
			int dwParam4, String strParam) {
		CLog.i(TAG, "OnAnyChatObjectEvent");
		switch (dwEventType) {
			case AnyChatObjectDefine.ANYCHAT_AGENT_EVENT_STATUSCHANGE:
				CLog.e(TAG, "dwEventType == ANYCHAT_AGENT_EVENT_STATUSCHANGE, " + dwObjectType + ", " + dwObjectId);
//				if (dwObjectId == mApplication.getUserID()) {
//					onDestroy();
//					finish();
//				}
				break;
		}
	}
}
